/*
 *  control.cpp
 *  projector
 *
 *  Created by Ilya Spivakov on 10/29/05.
 *  Copyright 2005 __MyCompanyName__. All rights reserved.
 *
 */

#include "bible_widget.h"
#include <QDir>
#include <QFile>
#ifdef Q_WS_MAC
#include <CoreFoundation/CoreFoundation.h>
#endif
#include <QPainter>






const char *book_names[66]={"Бытие","Исход","Левит","Числа","Второзаконие","Иисус Навин","Книга Судей","Руфь",	"1-я Царств","2-я Царств","3-я Царств","4-я Царств","1-я Паралипоменон","2-я Паралипоменон","Ездра","Неемия","Есфирь","Иов","Псалтирь","Притчи","Екклесиаст","Песни Песней","Исаия","Иеремия","Плач Иеремии","Иезекииль","Даниил","Осия","Иоиль","Амос","Авдий","Иона","Михей","Наум","Аввакум","Софония","Аггей","Захария","Малахия","От Матфея","От Марка","От Луки","От Иоанна","Деяния","Иакова","1-е Петра","2-е Петра","1-е Иоанна","2-е Иоанна","3-е Иоанна","Иуда","К Римлянам","1-е Коринфянам","2-е Коринфянам","К Галатам","К Ефесянам","К Филиппийцам","К Колоссянам","1-е Фессалоникийцам","2-е Фессалоникийцам","1-е Тимофею","2-е Тимофею","К Титу","К Филимону","К Евреям","Откровение"};


BibleWidget::BibleWidget(QWidget *parent)
        : QWidget(parent)
{

    codec = QTextCodec::codecForName("UTF8");
    book=0;
    chapter=1;
    verse=1;
    sync=FALSE;
    filename="./";
    //	verseList=new QStringList();
    ///////////get executable path (OS X)///////////////////
#ifdef Q_WS_MAC
    CFURLRef pluginRef = CFBundleCopyBundleURL(CFBundleGetMainBundle());
    CFStringRef macPath = CFURLCopyFileSystemPath(pluginRef,
                          kCFURLPOSIXPathStyle);
    const char *pathPtr = CFStringGetCStringPtr(macPath,
                          CFStringGetSystemEncoding());
    qDebug("Path = %s", pathPtr);
    CFRelease(pluginRef);
    CFRelease(macPath);


    filename= pathPtr;
#endif
    ////////////////////////////////////

    bible_grid=new QGridLayout(this);
    book_list_view=new QListWidget(this);
    //	debug_label=new QLabel(this);
    int x=0;
    while (x<66)
    {
        book_list_view->addItem(codec->toUnicode(book_names[x]));
        x++;
    }
    bible_grid->addWidget(book_list_view,0,0,10,1);
    //	bible_grid->addWidget(debug_label,10,10);
    chapter_selector=new QSpinBox();
    chapter_selector->setMinimum(1);
    verse_selector=new QSpinBox();
    verse_selector->setMinimum(1);
    QLabel *chapter_label=new QLabel("Chapter");
    QLabel *verse_label= new QLabel("Verse");
    verse_preview=new QLabel("Verse Preview");
    verse_preview->setWordWrap(TRUE);
    verse_preview->setFixedWidth(250);

    verse_preview_next=new QLabel("Verse Preview");
    verse_preview_next->setWordWrap(TRUE);
    verse_preview_next->setFixedWidth(250);
    verse_preview_next->setAlignment(Qt::AlignTop);

    verse_preview_prev=new QLabel("Verse Preview");
    verse_preview_prev->setWordWrap(TRUE);
    verse_preview_prev->setFixedWidth(250);


    bible_grid->addWidget(chapter_label,0,2);
    bible_grid->addWidget(verse_label,1,2);
    bible_grid->addWidget(chapter_selector,0,3);
    bible_grid->addWidget(verse_selector,1,3);

    bible_grid->addWidget(verse_preview_prev,5,2,2,2);
    bible_grid->addWidget(verse_preview,7,2,2,2);
    //verse_preview->setPalette(QPalette(QColor("BLUE"),QColor("BLACK")));
    verse_preview->setFrameShadow(QFrame::Sunken);
    verse_preview->setLineWidth(4);
    verse_preview->setFrameShape(QFrame::Panel);
    verse_preview->setMargin(3);
    bible_grid->setRowStretch(7,2);
    bible_grid->setRowStretch(5,1);
    bible_grid->setRowStretch(9,4);
    bible_grid->addWidget(verse_preview_next,9,2,2,2);
    show_hide_button=new QPushButton("HIDE!");
    show_hide_button->setCheckable(TRUE);
    sync_button=new QPushButton("SYNC");
    sync_button->setCheckable(TRUE);
    bible_grid->addWidget(sync_button,3,3,1,1);
    sync_button->setChecked(FALSE);
    connect(book_list_view,SIGNAL(currentRowChanged(int)),this,SLOT(change_book(int)));
    connect(chapter_selector,SIGNAL(valueChanged(int)),this,SLOT(change_chapter(int)));
    connect(verse_selector,SIGNAL(valueChanged(int)),this,SLOT(change_verse(int)));
    connect(show_hide_button,SIGNAL(toggled(bool)),this,SLOT(show_hide(bool)));
    connect(sync_button,SIGNAL(toggled(bool)),this,SLOT(sync_verse(bool)));
    show_hide_button->setChecked(1);
    bible_grid->addWidget(show_hide_button,3,2,1,1);


}


void BibleWidget::change_book(int value)
{
    //debug_label->setNum(value);
    QDir dir;
    dir.cd(filename+"/data/"+QString::number(value+1));
    QStringList files=dir.entryList(QDir::Files);
    chapter_selector->setMaximum(files.size());
    book=value;
    change_chapter(chapter);
    change_verse(verse);
    update_verse();
}

void BibleWidget::change_verse(int value)
{
    verse=value;
    //verse_preview->setText(verseList.at(verse-1));
    update_verse();
}

void BibleWidget::change_chapter(int value)
{
    chapter=value;
    QFile file( filename+"/data/"+QString::number(book+1)+"/"+QString::number(chapter)+".txt");
    codec = QTextCodec::codecForName("CP1251");
    verseList.clear();
    if ( file.open( QIODevice::ReadOnly ) )
    {

        while (!file.atEnd())
        {
            verseList << codec->toUnicode(file.readLine());
        }
        file.close();
        chapter=value;

    }
    verse_selector->setMaximum(verseList.size());
    update_verse();
}

void BibleWidget::update_verse()
{
    if (!verseList.isEmpty())
    {
        verse_preview->setText(verseList.at(verse-1));
        if (verseList.size()>verse)
        {
            verse_preview_next->setText(verseList.at(verse));
        }
        else
        {
            verse_preview_next->setText(" ");
        }
        if (verse>1)
        {
            verse_preview_prev->setText(verseList.at(verse-2));
        }
        else
        {
            verse_preview_prev->setText(" ");
        }
    }
    if (sync)show_hide(sync);

}


void BibleWidget::show_hide(bool show)
{
    if (show)
    {
        show_hide_button->setText("HIDE!");
        //sync=TRUE;
        //update_verse();
        codec=QTextCodec::codecForName("UTF8");
        QString text;
        text=verse_preview->text();
        text.chop(1);
        emit show_verse(text,codec->toUnicode(book_names[book_list_view->currentRow()])+" "+QString::number(chapter)+":"+QString::number(verse));
        //activateWindow ();
    }
    else
    {
        //sync=FALSE;
        show_hide_button->setText("SHOW!");
        emit show_verse(" "," ");
    }
}

void BibleWidget::sync_verse(bool val)
{
    sync=val;
    if (sync)
    {
        show_hide_button->setChecked(sync);
        update_verse();
    }
}








